import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { createSetPageErrorAction } from '@/redux/actions/pageError'
import MenuBar from '@/components/MenuBar'
import VideoPlayer from '@/components/VideoPlayer'
import VideoComment from '@/components/Comment'
import Loading from '@/components/Loading'
import VideoInfo from './info'
import VideoToolbar from './toolbar'
import VideoEpisode from './episode'
import VideoRelated from './related'
import { videoApi } from '@/api'
import { formatNumber } from '@/utils'
import css from './index.module.scss'
class Video extends PureComponent {

    state = {
        detailData: null,
        playUrl: null,
        videoTags: [],
        currentTab: 0,
        relatedVideos: [],
        videoComments: [],
        tabs: [
            { id: 1, title: '简介', other: '' },
            { id: 2, title: '评论', other: '' }
        ]
    }    

    initData = async () => {
        try {
            await this.getData()
            const { detailData } = this.state
            const redirectUrl = detailData.redirect_url
            if (typeof redirectUrl !== 'undefined') {
                // 跳转番剧详细页
                const id = redirectUrl.substring(redirectUrl.lastIndexOf('/') + 1)
                this.props.history.push(`/bangumi/${id}`)
            } else if (detailData){
                await Promise.all([
                    this.getPlayUrl(),
                    this.getVideoTags(),
                    this.getVideoRelated()
                    // this.getVideoComments()
                ])  
            }                   
        } catch (error) { 
            this.props.setPageError(true)         
        }
    }

    // 获取视频详细信息
    getData = async () => {
        try {
            const { match: { params: { bvid } } } = this.props    
            const { data } = await videoApi.getVideo({
                bvid
            })
            const { tabs } = this.state
            tabs[1].other = formatNumber(data.stat.reply)
            this.setState({
                detailData: data,
                tabs: [...tabs]
            })
        } catch (error) {
           console.log(error)
           throw new Error(error)
        }        
    }
    // 获取播放地址
    getPlayUrl = async ({ aid, bvid, cid } = {}) => {
        try {
            const { detailData } = this.state
            if (!aid && !bvid && !cid) {
                aid = detailData.aid
                bvid = detailData.bvid
                cid = detailData.cid
            }
            const { data } = await videoApi.getPlayUrl({
                avid: aid,
                bvid,
                cid
            })
            if (!data) {
                return
            }
            const { durl } = data
            this.setState({
                playUrl: durl[0].url
            })

        } catch (error) {

        }
    }

    // 获取视频标签
    getVideoTags = async () => {
        try {
            const { detailData } = this.state
            const { aid, bvid } = detailData
            const { data } = await videoApi.getVideoTags({
                aid,
                bvid
            })
            if (!data) {
                return
            }
            this.setState({
                videoTags: data
            })

        } catch (error) {            
        }
    }

    // 获取相关视频
    getVideoRelated = async () => {
        try {
            const { detailData } = this.state
            const { aid, bvid } = detailData
            const { data } = await videoApi.getVideoRelated({
                aid,
                bvid
            })
            if (!data) {
                return
            }
            this.setState({
                relatedVideos: data.slice(0, 40)
            })

        } catch (error) {            
        }
    }

    // 获取视频评论
    getVideoComments = async () => {
        try {
            const { detailData } = this.state
            const { aid, bvid } = detailData
            const { data } = await videoApi.getVideoComments({
                oid: aid,
                bvid
            })
            if (!data) {
                return
            }            
            this.setState({
                videoComments: data.replies
            })

        } catch (error) {            
        }
    }

    handleTabClick = (tab, index) => {
        this.setState({
            currentTab: index
        }, () => {
            if (index === 1 && !this.state.videoComments.length) {
                // 初次加载评论
                this.getVideoComments()
            } 
        })
    }

    handleTabRender = tab => {
        return (
            <span style={{'whiteSpace': 'nowrap', 'overflow': 'hidden', 'textOverflow': 'ellipsis'}}>
                {tab.title} {tab.other}
            </span>
        )
    }

    handleEpisode = episode => {
        const { detailData } = this.state
        this.getPlayUrl({
            aid: detailData.aid,
            bvid: detailData.bvid,
            cid: episode.cid
        })
    }
    
    componentDidMount() {
        this.initData()
    }

    componentDidUpdate(prevProps) {
        const { match: { params: { bvid } } } = this.props    
        if (prevProps.match.params.bvid !== bvid) {
            this.initData()
        }        
    }

    render() {
        const { detailData, videoTags, playUrl, currentTab, tabs, relatedVideos, videoComments } = this.state                
        return (
            <>                
                { 
                    detailData && 
                    playUrl && 
                    <div className={css['sticky']}>
                        <VideoPlayer url={playUrl} 
                            poster={detailData.pic} 
                            duration={detailData.duration} 
                        /> 
                    </div>
                }

                {
                    detailData && (
                        <MenuBar 
                            tabs={tabs} 
                            currentTab={currentTab} 
                            swipeable={false}
                            onTabClick={this.handleTabClick}
                            renderTab={this.handleTabRender}
                        >
                            <div>
                                <VideoInfo detailData={detailData} tags={videoTags}/>
                                <VideoToolbar detailData={detailData} />
                                <VideoEpisode detailData={detailData} onSelect={this.handleEpisode} />                          
                                { relatedVideos.length > 0 && <VideoRelated videos={relatedVideos} /> }   
                            </div>
                            
                            <div>                                    
                                { videoComments.length ? <VideoComment comments={videoComments} /> : <Loading /> }
                            </div>
                        </MenuBar>
                    )
                }                                   
            </>
        )                                   
    }
}

export default connect(
    null,
    {
        setPageError: createSetPageErrorAction
    }
)(Video)